CODE 68. Merge Two Sorted Lists

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/07/2013-10-07-CODE 68 Merge Two Sorted Lists/

访问原文「CODE 68. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes
of the first two lists.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
if (null == l1 && null == l2) {
return null;
} else if (null == l2) {
return l1;
} else if (null == l1) {
return l2;
}
ListNode newList = new ListNode(0);
ListNode p = newList;
ListNode p1 = l1;
ListNode p2 = l2;
while (null != p1 && null != p2) {
if (p1.val < p2.val) {
ListNode node = new ListNode(p1.val);
p.next = node;
p = p.next;
p1 = p1.next;
} else {
ListNode node = new ListNode(p2.val);
p.next = node;
p = p.next;
p2 = p2.next;
}
}
if (null != p1) {
p.next = p1;
} else if (null != p2) {
p.next = p2;
}
return newList.next;
}
Jerky Lu wechat
欢迎加入微信公众号